package com.hopu.mcshipin.service.impl;

import com.hopu.mcshipin.entity.Gender;
import com.hopu.mcshipin.entity.R;
import com.hopu.mcshipin.entity.User;
import com.hopu.mcshipin.exception.BusinessException;
import com.hopu.mcshipin.mapper.UserMapper;
import com.hopu.mcshipin.service.UserService;
import com.hopu.mcshipin.util.ErrorCode;
import com.hopu.mcshipin.util.PasswordUtil;
import com.hopu.mcshipin.util.ValidationUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public R login(User user) {
        String name = user.getName();
        String password = user.getPassword();

        ValidationUtil.validateUsername(name);
        ValidationUtil.validatePassword(password);


        List<User> userList = userMapper.selectUserByName(name);
        if (userList == null || userList.isEmpty()) {
            throw new BusinessException(ErrorCode.USER_NOT_EXIST);
        }

        User dbUser = userList.get(0);


        if (!PasswordUtil.verify(password, dbUser.getPassword())) {
            throw new BusinessException(ErrorCode.PASSWORD_ERROR);
        }

        User responseUser = new User();
        responseUser.setId(dbUser.getId());
        responseUser.setName(dbUser.getName());
        responseUser.setPhone(dbUser.getPhone());

        return R.ok("登录成功", responseUser);
    }

    @Override
    @Transactional
    public R register(User user) {
            // 参数校验
            ValidationUtil.requireNonNull(user, ErrorCode.PARAM_IS_NULL);
            ValidationUtil.validateUsername(user.getName());
            ValidationUtil.validatePassword(user.getPassword());
            ValidationUtil.validatePhone(user.getPhone());

            // 检查用户是否存在
            List<User> existingUsers = userMapper.selectUserByName(user.getName());
            if (!existingUsers.isEmpty()) {
                throw new BusinessException(ErrorCode.USERNAME_ALREADY_EXISTS);
            }

            // 密码加密
            String encryptedPassword = PasswordUtil.encrypt(user.getPassword());
            user.setPassword(encryptedPassword);

            // 设置默认值
            user.setFollowCount(0);
            user.setCollectionCount(0);
            user.setIsAutor(0);
            user.setAge(0);
            user.setAddress("");
            user.setLove("");
            user.setGender(Gender.男);
            user.setNickname("jim");
            user.setUrl("");
            user.setStatus(1); // 激活状态
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());

            // 执行插入
            userMapper.register(user);
            return R.ok("注册成功");

    }
}
